package com.ctz.commonframe.utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

/**
 * 文件获取工具，用于获取本地文件（图片，视频，音频），拍照获取图片
 */
public class FilePickUtil {
	private static final String PREFIX_IMAGE = "IMAGE_";
	private static final String SUFFIX_IMAGE = ".jpg";
	private static final String PREFIX_VIDEO = "VIDEO_";
	private static final String SUFFIX_VIDEO = ".mp4";
	private static final String PREFIX_SOUND = "SOUND_";
	private static final String SUFFIX_SOUND = ".mp3";
	private static final String FOLDER_CACHE = "Cache";
	private static final String FOLDER_ATTACHMENT = "Attachment";
	private static final String FOLDER_TEMP = "Temp";
	private static final String FOLDER_DOWNLOAD = "Download";
	private static final String FOLDER_UPLOAD = "Upload";
	
	public static String getCacheFolder(Context context){
		return context.getPackageName() + File.separator + FOLDER_CACHE;
	}
	
	public static String getAttachmentFolder(Context context){
		return context.getPackageName() + File.separator + FOLDER_ATTACHMENT; 
	}
	
	public static String getTempFolder(Context context){
		return context.getPackageName() + File.separator + FOLDER_TEMP;
	}
	
	public static String getDownloadFolder(Context context){
		return context.getPackageName() + File.separator + FOLDER_DOWNLOAD;
	}
	
	public static String getUploadFolder(Context context){
		return context.getPackageName() + File.separator + FOLDER_UPLOAD;
	}
	
	public static String getImageName(long currentTime){
		return PREFIX_IMAGE + currentTime + SUFFIX_IMAGE;
	}
	
	public static String getVideoName(long currentTime){
		return PREFIX_VIDEO + currentTime + SUFFIX_VIDEO;
	}
	
	public static String getSoundName(long currentTime){
		return PREFIX_SOUND + currentTime + SUFFIX_SOUND;
	}
	
	public static String getTakePhotoPath(Context context, String folderName, String fileName){
		String externalDir = SDCardUtil.getSDCardPath(context);
		if(TextUtils.isEmpty(externalDir)){
			return null;
		}
		File file = new File(externalDir + File.separator + folderName + File.separator + fileName);
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		return file.getAbsolutePath();
	}
	
	public static Intent createTakePhotoIntent(Context context, String path) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(path)));
		return intent;
	}
	
	public static File handleTakePhotoResult(String path){
		return compressFile(path);
	}
	
	private static File compressFile(String path) {
		Bitmap compressBitmap = decodeFile(path);
		Bitmap newBitmap = ratingImage(path, compressBitmap);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		newBitmap.compress(CompressFormat.PNG, 100, os);
		byte[] bytes = os.toByteArray();
		
		File file = null ;
		try {
			file = getFileFromBytes(bytes, path);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(newBitmap != null ){
				if(!newBitmap.isRecycled()){
					newBitmap.recycle();
				}
				newBitmap  = null;
			}
			if(compressBitmap != null ){
				if(!compressBitmap.isRecycled()){
					compressBitmap.recycle();
				}
				compressBitmap  = null;
			}
		}
		return file;
	}
	
	@SuppressWarnings("deprecation")
	private static Bitmap decodeFile(String path) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		opts.inDither = false; // Disable Dithering mode
		opts.inPurgeable = true; // Tell to gc that whether it needs free
		opts.inInputShareable = true; // Which kind of reference will be used to
		BitmapFactory.decodeFile(path, opts);
		final int REQUIRED_SIZE = 200;
		int scale = 1;
		if (opts.outHeight > REQUIRED_SIZE || opts.outWidth > REQUIRED_SIZE) {
			final int heightRatio = Math.round((float) opts.outHeight
					/ (float) REQUIRED_SIZE);
			final int widthRatio = Math.round((float) opts.outWidth
					/ (float) REQUIRED_SIZE);
			scale = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		opts.inJustDecodeBounds = false;
		opts.inSampleSize = scale;
		Bitmap bm = BitmapFactory.decodeFile(path, opts).copy(Config.ARGB_8888, false);
		return bm;
	}
	
	/**
	 * 读取图片属性：旋转的角度
	 * @param path 图片绝对路径
	 * @return degree旋转的角度
	 */
    private static int readPictureDegree(String path) {
        int degree  = 0;
        try {
                ExifInterface exifInterface = new ExifInterface(path);
                int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }
        } catch (IOException e) {
                e.printStackTrace();
        }
        return degree;
    }
    
    private static Bitmap ratingImage(String filePath, Bitmap bitmap){
		int degree = readPictureDegree(filePath);
		return rotaingImageView(degree, bitmap);
	}
	
	/**
	 *  旋转图片
	 * @param angle
	 * @param bitmap
	 * @return Bitmap
	 */
	public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
        //旋转图片 动作
		Matrix matrix = new Matrix();;
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        		bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}
	
	/**
	 * 把字节数组保存为一个文件
	 * 
	 * @param b
	 * @param outputFile
	 * @return
	 */
	public static File getFileFromBytes(byte[] b, String outputFile) {
		File ret = null;
		BufferedOutputStream stream = null;
		try {
			ret = new File(outputFile);
			FileOutputStream fstream = new FileOutputStream(ret);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return ret;
	}
}	
